package com.longk.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.longk.access.Access;
import com.longk.common.ReturnCoverImageVo;
import com.longk.common.ReturnImageUploadVO;
import com.longk.common.ReturnVO;
import com.longk.dao.ArticleMapper;
import com.longk.dao.UserMapper;
import com.longk.moduel.Article;
import com.longk.moduel.User;

@RestController
@RequestMapping("/cd")

public class AdminController {
	@Autowired
	ArticleMapper articleMapper;
	@Autowired
	UserMapper userMapper;
	String path = "f:/upload";
	@Access
	@RequestMapping("/editor")
	public ModelAndView editor(HttpServletRequest request) {
        String id =request.getParameter("acticleId");
        if(!StringUtils.isEmpty(id)) {
        	
        	
       Article art= 	articleMapper.selectArticleById(Integer.parseInt(id));
         if(art!=null) {
        	 
        	 
        	 
         request.setAttribute("acticle", art);       	 
        	 
        	 
        	 
         ModelAndView view = new ModelAndView("/editor_w_e.btl");	 
        	 
        	 return view;
         }
       
       
       
        }
        
		ModelAndView view = new ModelAndView("/editor_w.btl");
		
		return view;
	}

	
	
	@Access
	@RequestMapping("/article/save")

	public ReturnVO save(HttpServletRequest request) {
		String operation = request.getParameter("op");
		if (StringUtils.isEmpty(operation)) {
			return ReturnVO.getVO(-500, false);
		}
		String title = request.getParameter("title");
		String keywords = request.getParameter("keyword");
		String content = request.getParameter("content");
		String text = request.getParameter("text");
		String type = request.getParameter("type");
		String cover = request.getParameter("cover");
		Article art = new Article();
		if (operation.equals("A")) {

			art.setContent(content);
			art.setCreateTime(new Date());
			art.setModifyTime(new Date());
			art.setTitle(title);
			art.setText(text);
			art.setKeywords(keywords);
			art.setUserId("longky");
			art.setType(type);
			art.setCover(cover);
			articleMapper.insertArticle(art);
		} else if (operation.equals("U")) {
			String id = request.getParameter("acticleId");
			art.setContent(content);
			art.setModifyTime(new Date());
			art.setTitle(title);
			art.setKeywords(keywords);
			art.setType(type);
			art.setText(text);
			art.setCover(cover);
			articleMapper.update(Integer.parseInt(id), art);
			return ReturnVO.getVO(art.getArticleId(), true);
		}
		return ReturnVO.getVO(-500, false);
	}
	
	@Access
	@RequestMapping("/article/delete")

	public ReturnVO delete(@RequestParam("id") int id) {
		articleMapper.deleteFaker(id);
		return ReturnVO.getVO(id, true);
	}
	
	@Access
	@RequestMapping(value = "/upload", method = RequestMethod.POST)

	public ReturnImageUploadVO handleFileUpload(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		ArrayList paths = new ArrayList<String>();
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					String fileName = getRandomFileName()+file.getOriginalFilename().split(".")[1];
					String destpath = path + "/" + fileName;
					File dest = new File(destpath);
					if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
						dest.getParentFile().mkdir();
					}
					stream = new BufferedOutputStream(new FileOutputStream(dest));
					stream.write(bytes);
					stream.close();
					paths.add(fileName);
					System.out.println(destpath);
					System.out.println(dest.getPath());
				} catch (Exception e) {
					stream = null;
					return new ReturnImageUploadVO(500, paths);
				}
			} else {
				return new ReturnImageUploadVO(510, paths);
			}

		}
		return new ReturnImageUploadVO(0, paths);
	}
@Access
	@RequestMapping(value = "/upload2", method = RequestMethod.POST)

	public ReturnCoverImageVo coverPicUpload(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("coverpic");
		String acticleId = request.getParameter("acticleId");
		MultipartFile file = null;
		BufferedOutputStream stream = null;
		ArrayList paths = new ArrayList<String>();
		String destPath = "";
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					String fileName = getRandomFileName()+"."+file.getOriginalFilename().split("\\.")[1];

					String destpath = path + "/" + fileName;
					File dest = new File(destpath);
					if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
						dest.getParentFile().mkdir();
					}
					stream = new BufferedOutputStream(new FileOutputStream(dest));
					stream.write(bytes);
					stream.close();
					paths.add(destpath);
					destPath = fileName;
				} catch (Exception e) {
					stream = null;
					e.printStackTrace();
					return new ReturnCoverImageVo(false, destPath);
				
				}
			} else {
				return new ReturnCoverImageVo(true, destPath);
			}
		}

		return new ReturnCoverImageVo(true, destPath);
	}
@Access
	@RequestMapping("/articles/")

	public ModelAndView list(HttpServletRequest request, int page, int size) {
		ModelAndView view = new ModelAndView("/articleList.btl");
      
		List<Article> list = articleMapper.selectArticle((page - 1) * size, size);
		request.setAttribute("acticleList", list);
		return view;

	} 
	
	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/login2.btl");
	    request.setAttribute("errMessage", request.getAttribute("errMessage"));
		return view;

	}
	
	@RequestMapping("/loginaction")
	public ModelAndView loginAction(HttpServletRequest request,HttpServletResponse response,@RequestParam("username")String username,@RequestParam("password")String password) {
		ModelAndView view; 
       if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
    	   
    	  
    	   return new ModelAndView("/login");
       }
       else {
    	User user=   userMapper.getUserByUsernameAndPass(username, password);
    	request.getSession().setAttribute("user", user);
    	   if(user==null) {
    		   request.setAttribute("errMessage", "帐号密码错误");
    		   return new ModelAndView("/login2.btl");
    	   }else {
    		   
    		   
    		   return new ModelAndView("/index");
    	   }
    	   
       }

	}
	
	
	public static String getRandomFileName() {  
		  
        SimpleDateFormat simpleDateFormat;  
  
        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");  
  
        Date date = new Date();  
  
        String str = simpleDateFormat.format(date);  
  
        Random random = new Random();  
  
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数  
  
        return rannum + str;// 当前时间  
    }  
}
